// pages/cl/cl.js
const base64 = require("base64.modified.js");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: app.globalData.url,
    connect: 0,//0未连接 1链接成功 2链接失败
    list: [],//deviceslist
    switchChecked: false,
    DevicesConnected: [{
      DevicesDisplay: "none",
      name: "",
      deviceId: "",
    }],
    Taglist: [],
    deviceId: "",
    serviceId: "",
    readCharacteristicId: "",
    notifyCharacteristicId: "",
    notify: false,
    services: [],
    characteristics: [],
    connectDeviceIndex: 0,
    connectCharacteristic: 0,
    readServices: [],
    readcharacteristics: [],
    tips: '请插入试纸',
    isShow: true,
    testType: '血糖 ',
    testCode: 'Blood_Sugar',
    cqch: 0,//0餐前1餐后
    cljg: 3.1,
    yscljg: 0,
    commons: [],
    testTime: 0,
    ksclText: '请在设备上开始测量'
  },
  //开始或关闭搜索附近的蓝牙设备
  BluetoothSwitchChange: function (e) {
    var that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        that.onBluetoothAdapterStateChange();//监听蓝牙适配器状态变化事件
        that.getBluetoothAdapterState();
      },
      fail: function (err) {
        that.setData({
          'switchChecked': false
        });

        wx.showModal({
          title: '错误',
          content: '初始化蓝牙失败，请检查是否开启蓝牙设备',
        })
      }
    });
  },
  closeBlueTooth: function (e) {
    var that = this;
    //关闭蓝牙模块--断开与低功耗蓝牙设备的连接
    wx.closeBluetoothAdapter({
      success: function (res) {
        that.setData({
          'list': [],
          'DevicesConnected': [{
            DevicesDisplay: "none",
            name: "",
            deviceId: "",
          }],
          connect: 0
        });
      }
    })
  },
  //监听蓝牙适配器状态变化事件
  onBluetoothAdapterStateChange: function () {
    wx.onBluetoothAdapterStateChange(function (res) {
      var available = res.available;
      if (!available) {
        wx.showModal({
          title: '提示',
          content: '蓝牙已断开',
        })
      }
    })
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState: function () {
    var that = this;
    wx.getBluetoothAdapterState({
      success: function (res) {
        var available = res.available;//蓝牙适配器是否可用
        var discovering = res.discovering;//是否正在搜索设备
        if (!available) {
          wx.showModal({
            title: '错误',
            content: '蓝牙适配器状态不可用',
          })
        }
        if (!discovering) {
          that.startBluetoothDevicesDiscovery();
        }
      }
    })
  },
  //开始搜寻附近的蓝牙外围设备。注意，该操作比较耗费系统资源，请在搜索并连接到设备后调用 stop 方法停止搜索。
  startBluetoothDevicesDiscovery: function () {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      // services: [],
      success: function (res) {
        if (res.isDiscovering) {
          that.getBluetoothDevices();
        }
      },
      fail: function (err) {
        wx.showModal({
          title: '错误',
          content: '搜寻附近的蓝牙外围设备失败',
        });
        that.closeBlueTooth();
      }
    })
  },
  //获取所有已发现的蓝牙设备  
  getBluetoothDevices: function () {
    var that = this;
    var length = 0;
    var count = 0;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    var deviceslist = [];
    setTimeout(
      function () {
        wx.getBluetoothDevices({
          success: function (res) {
            var devices = res.devices;
            if (devices.length == 0) {
              wx.hideLoading();
              return;
            }
            for (var i = 0; i < devices.length; i++) {
              if (devices[i] != null && devices[i]['name'].indexOf('Laya') != -1) {
                deviceslist = new Array(devices[i]);
                break;
              }
            }
            that.setData({
              'list': deviceslist
            });
            that.createBLEConnection();
          },
          fail: function (res) {
            that.closeBlueTooth();
            wx.hideLoading();
          }
        })
      }, 2000) //搜寻设备5秒
  },
  //连接低功耗蓝牙设备  
  createBLEConnection: function () {
    var that = this;
    if (this.data.list.length <= 0) {
      this.setData({
        connect: 2
      });
      that.closeBlueTooth();
      wx.hideLoading();
      return;
    }
    var obj = this.data.list[0];
    var name = obj['name'];
    var deviceId = obj['deviceId'];

    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
        that.setData({
          'DevicesConnected': [{
            DevicesDisplay: "block",
            name: name,
            deviceId: deviceId,
          }]
        });
        getApp().data.deviceId = obj.deviceId//全局变量赋值
        that.Inventory();
      },
      fail: function (err) {
        wx.showModal({
          title: '错误',
          content: '连接失败',
        });
        that.setData({
          connect: 2
        });
        that.closeBlueTooth();
        wx.hideLoading();
      },
    })
  },
  Inventory: function () {
    var that = this;
    that.setData({
      Taglist: []
    })
    var deviceId = getApp().data.deviceId;//全局变量
    that.setData({
      deviceId: deviceId
    })
    if (deviceId == "") {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '未连接蓝牙设备,请连接蓝牙设备',
      });
      return
    }
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: that.data.deviceId,
      success: function (res) {
        that.setData({
          services: res.services
        });
        that.loopConnect(that.data.connectDeviceIndex);
      },
      fail: function (res) {
        wx.hideLoading();
        that.closeBlueTooth();
      }
    });
    that.ax()
  },


  ax: function () {
    var that = this;
    var tips = '请插入试纸';
    wx.onBLECharacteristicValueChange(function (res) {
      var TaglistArray = that.data.Taglist;
      //处理数据，将Arraybuffer转换为base64，在将base64转换为字符串              
      var base64str = base64.decode(wx.arrayBufferToBase64(res.value))//base64解密
      var common = base64str;
      var commons = that.data.commons;
      commons.push(base64str);
      that.setData({
        commons: commons
      });
      if (common == 'TextPaperIN\r\n') {
        //插入试纸
        tips = '试纸已插入，请开始滴入血液';
        that.setData({
          Taglist: [],
        })
      } else if (common == 'Blood_Sugar\r\n6\r\n') {
        tips = '试纸种类：血糖';
        that.setData({
          testType: '血糖 ',
          testCode: 'Blood_Sugar',
          testTime: 6
        });
        tips = '测量时间为：' + 6 + '秒';
      } else if (common == 'Cholesterol\r\n60\r\n') {
        tips = '试纸种类：胆固醇';
        that.setData({
          testType: '胆固醇 ',
          testCode: 'Cholesterol',
          testTime: 60
        });
        tips = '测量时间为：' + 60 + '秒';
      } else if (common == 'Uric_Acid\r\n20\r\n') {
        tips = '试纸种类：尿酸';
        that.setData({
          testType: '尿酸 ',
          testCode: 'Uric_Acid',
          testTime: 20
        });
        tips = '测量时间为：' + 20 + '秒';
      } else if (common == 'Triglyceride\r\n90\r\n') {
        tips = '试纸种类：甘油三酯';
        that.setData({
          testType: '甘油三酯 ',
          testCode: 'Triglyceride',
          testTime: 90
        });
        tips = '测量时间为：' + 90 + '秒，请滴入液体';
      } else if (common == 'DropLiquid\r\n') {
        tips = '已滴入液体，请等待测量结果';
        setTimeout(function () {
          var lastTime = that.data.testTime - 1;
          that.setData({
            testTime: lastTime
          });
        }, 1000);
      } else if (common.indexOf('TextOver\r\n') != -1) {
        tips = '测量结束'
      } else if (!isNaN(common.replace('\r\n', '')) && that.data.Taglist[that.data.Taglist.length - 1] == '测量结束') {
        var result = parseInt(common.replace('\r\n', ''));
        tips = '测量结果为：' + that.convert(that.data.testCode, result) + (that.data.testCode == 'Uric_Acid' ? 'umol/L' : 'mmol/L');
        that.setData({
          cljg: that.convert(that.data.testCode, result),
          yscljg: that.convert3(that.data.testCode, result),
        });
        that.setData({
          isShow: false,
          ksclText: '测量成功'
        });
      } else if (common == 'TextPaperOut\r\n') {
        tips = '试纸已拔出';
      } else if (common.startsWith('Blood_Sugar\r\n6\r\n')) {
        var str = common.split("\r\n")
        var result = str[2]
        that.setData({
          isShow: false,
          testType: '血糖 ',
          testCode: 'Blood_Sugar',
          cljg: that.convert('Blood_Sugar', result),
          yscljg: that.convert3('Blood_Sugar', result),
          ksclText: '测量成功'
        });
      } else if (common.startsWith('Cholesterol\r\n60\r\n')) {
        var str = common.split("\r\n")
        var result = str[2]
        that.setData({
          isShow: false,
          testType: '胆固醇 ',
          testCode: 'Cholesterol',
          cljg: that.convert('Cholesterol', result),
          yscljg: that.convert3('Cholesterol', result),
          ksclText: '测量成功'
        });
      } else if (common.startsWith('Uric_Acid\r\n20\r\n')) {
        var str = common.split("\r\n")
        var result = str[2]
        that.setData({
          isShow: false,
          testType: '尿酸 ',
          testCode: 'Uric_Acid',
          cljg: that.convert('Uric_Acid', result),
          yscljg: that.convert3('Uric_Acid', result),
          ksclText: '测量成功'
        });
      } else if (common.startsWith('Triglyceride\r\n90\r\n')) {
        var str = common.split("\r\n")
        var result = str[2]
        that.setData({
          isShow: false,
          testType: '尿酸 ',
          testCode: 'Triglyceride',
          cljg: that.convert('Triglyceride', result),
          yscljg: that.convert3('Uric_Acid', result),
          ksclText: '测量成功'
        });
      } else {
        tips = that.errors(common);
      }
      TaglistArray.push(tips)
      that.setData({
        Taglist: TaglistArray,
      })
      that.setData({
        tips: tips
      });
    })
  },
  confirm: function () {
    //TODO..
    var self = this;
    this.setData({
      isShow: true
    });
    var threeSession = app.get3Session();
    if (self.data.testCode != 'Blood_Sugar') {
      self.setData({
        cqch: 0
      });
    }
    wx.request({
      url: app.globalData.domain + 'test/save?threeSession=' + threeSession + "&type=" + self.data.testCode + "&value=" + self.data.yscljg + "&cqch=" + self.data.cqch,
      dataType: 'json',
      success: function (data) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
        self.setData({
          cqch: 0
        });
      },
      fail: function (data) {
        wx.showToast({
          title: '保存失败',
          icon: 'none',
          duration: 2000
        })
        self.setData({
          cqch: 0
        });
      }
    });
  },
  cancel: function () {
    this.setData({
      isShow: true,
      tips: '',
      Taglist: [],
      testType: '血糖 ',
      testCode: 'Blood_Sugar',
      cqch: 0,
      cljg: 0
    });
  },
  // show:function(){
  //   this.setData({
  //     isShow: false
  //   });
  // },

  errors: function (common) {
    var result = '';
    if (common == 'ERR1\r\n') {
      result = '开机自检异常'
    } else if (common == 'ERR2\r\n') {
      result = '试纸过期或已使用'
    } else if (common == 'ERR3\r\n') {
      result = '滴血测量操作有误'
    } else if (common == 'ERR4\r\n') {
      result = '系统错误'
    } else if (common == 'ERR5\r\n') {
      result = '通讯异常'
    } else {
      return this.data.tips
    }
    return result;
  },

  convert: function (common, value) {
    var result = '';
    if (common == 'Blood_Sugar') {
      result = (value / 18).toFixed(1)
    } else if (common == 'Cholesterol') {
      result = (value / 38.67).toFixed(1)
    } else if (common == 'Uric_Acid') {
      result = (value / 0.01681 / 10).toFixed(0)
    } else if (common == 'Triglyceride') {
      result = (value / 88.545).toFixed(1)
    }
    return result;
  },
  convert3: function (common, value) {
    var result = '';
    if (common == 'Blood_Sugar') {
      result = (value / 18).toFixed(3)
    } else if (common == 'Cholesterol') {
      result = (value / 38.67).toFixed(3)
    } else if (common == 'Uric_Acid') {
      result = (value / 0.01681 / 10).toFixed(3)
    } else if (common == 'Triglyceride') {
      result = (value / 88.545).toFixed(3)
    }
    return result;
  },
  radioChange: function (e) {
    var cqch = e.target.dataset.cqch
    this.setData({
      cqch: cqch
    });
  },
  ab2hex: function (buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  readdata: function () {
    var that = this;
    wx.readBLECharacteristicValue({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  [**new**]
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.serviceId,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: that.data.readCharacteristicId,
      success: function (res) {
      }
    });
  },

  loopConnect: function (index) {
    var that = this;
    if (index >= that.data.services.length) {
      wx.hideLoading();
      wx.showToast({
        title: '连接成功',
        icon: 'success',
      })
      this.setData({
        connect: 1
      });
      return
    }
    var serviceId = that.data.services[index].uuid//设置serviceId的值     
    that.setData({
      serviceId: serviceId
    })
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.serviceId,
      success: function (res) {
        that.setData({
          characteristics: res.characteristics
        });
        that.loopCharacteristics(0);
      },
      fail: function (res) {
      }
    })
  },

  loopCharacteristics: function (y) {
    var that = this;
    if (y >= this.data.characteristics.length) {
      var next = this.data.connectDeviceIndex + 1;
      this.setData({
        connectDeviceIndex: next
      });
      that.loopConnect(that.data.connectDeviceIndex);
      return;
    }
    var characteristic = this.data.characteristics[y];
    if (characteristic.properties.notify) {
      that.setData({
        readCharacteristicId: characteristic.uuid,
      });
      that.setData({
        notifyCharacteristicId: characteristic.uuid,
      });
      wx.notifyBLECharacteristicValueChange({
        state: true, // 启用 notify 功能
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
        deviceId: that.data.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接s口中获取
        serviceId: that.data.serviceId,
        // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        characteristicId: that.data.notifyCharacteristicId,
        success: function (res) {
          // 必须在这里的回调才能获取
          var isContains = that.contains(that.data.readServices, that.data.serviceId);
          var isContainsC = that.contains(that.data.readcharacteristics, that.data.notifyCharacteristicId);
          if (!(isContains && isContainsC)) {
            var arr = that.data.readServices;
            arr.push(that.data.serviceId);
            that.setData({
              readServices: arr
            });
            var arr = that.data.readcharacteristics;
            arr.push(that.data.serviceId);
            that.setData({
              readcharacteristics: arr
            });
            wx.readBLECharacteristicValue({
              // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  [**new**]
              deviceId: that.data.deviceId,
              // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
              serviceId: that.data.serviceId,
              // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
              characteristicId: that.data.readCharacteristicId,
              success: function (res) {

              }
            });
          }
        },
        fail: function (res) {
         
        },
        complete: function (res) {
          //下一个
          var next = that.data.connectCharacteristic + 1;
          that.setData({
            connectCharacteristic: next
          });
          that.loopCharacteristics(that.data.connectCharacteristic);
        }
      })
    } else {
      var next = that.data.connectCharacteristic + 1;
      that.setData({
        connectCharacteristic: next
      });
      that.loopCharacteristics(this.data.connectCharacteristic);
    }
  },

  onBLEConnectionStateChange: function () {
    var self = this;
    wx.onBLEConnectionStateChange(function (res) {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      if (!res.connected) {
        self.closeBlueTooth();
      }
    })
  },
  contains: function (arr, obj) {
    var i = arr.length;
    while (i--) {
      if (arr[i] === obj) {
        return true;
      }
    }
    return false;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.connect == 0 || this.data.connect == 2) {
      this.BluetoothSwitchChange();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.closeBlueTooth();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.closeBlueTooth();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onShareAppMessage: function (ops) {
    if (ops.from === 'button') {
      // 来自页面内转发按钮

    }
    return {
      title: 'MEDATA',
      path: 'pages/step/step',
      success: function (res) {
        // 转发成功

      },
      fail: function (res) {
        // 转发失败

      }
    }
  },
})